<?php
namespace jy_merch;
defined('BY_JYA') or exit('error');
/*
*/
class wxwork extends \plugin{
	
	/*
		获取企业永久授权码 返回的信息
	*/
	public function upitem($merchid=0,$content=array(),$pluginname='',$pid=''){
		$merchid=$merchid?:$_SESSION['onemerchid'];
		if(!$merchid){
		    $mid=pdo_getcolumn('core_fans',array('userid'=>trim($content['auth_user_info']['userid']),'corpid'=>trim($content['auth_corp_info']['corpid']),'type'=>9,'uniacid'=>$_SESSION['uniacid'],'isopen'=>1),'mid');
			if(!$mid){
				$mid=pdo_getcolumn('core_fans',array('corpid'=>trim($content['auth_corp_info']['corpid']),'type'=>9,'uniacid'=>$_SESSION['uniacid'],'isopen'=>1),'mid');
			}
			$merchid=pdo_getcolumn('jy_merch_user',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'id');
			if(!$merchid){
			   return false; 
			}
		}
		$wxwork=pdo_get('core_account_wxwork',array('merchid'=>$merchid,'uniacid'=>$_SESSION['uniacid']));
		$data=array(
			'title'=>$content['auth_corp_info']['corp_name']?:$wxwork['title'],
			'logo'=>$content['auth_corp_info']['corp_square_logo_url']?:$wxwork['logo'],
			'appid'=>trim($content['auth_corp_info']['corpid']),
		);
		if($wxwork['id']){
			pdo_update('core_account_wxwork',$data,array('merchid'=>$merchid,'uniacid'=>$_SESSION['uniacid']));
		}else{
			$data['uniacid']=$_SESSION['uniacid'];
			$data['merchid']=$merchid;
			$data['token']=random(30);
			$data['aeskey']=random(43);
			$data['createtime']=TIMESTAMP;
			pdo_insert('core_account_wxwork',$data);
			$wxwork['id']=pdo_insertid();
		}
		$pid=$pid?:pdo_getcolumn('core_plugins',array('name'=>$pluginname),'id');
		$wxwork_app=pdo_get('core_account_wxwork_app',array('pid'=>$pid,'merchid'=>$merchid,'uniacid'=>$_SESSION['uniacid']));
		$data=array(
			'title'=>$content['auth_info']['agent'][0]['name']?:$wxwork_app['title'],
			'logo'=>$content['auth_info']['agent'][0]['square_logo_url']?:$wxwork_app['logo'],
			'appid'=>$content['auth_info']['agent'][0]['agentid']?:$wxwork_app['appid'],
			'permanent_code'=>$content['permanent_code']?:$wxwork_app['permanent_code'],
			'wxwork_id'=>$wxwork['id'],
		);
		$saastype=pdo_getcolumn('core_open_plugin',array('pid'=>$pid,'uniacid'=>$_SESSION['uniacid'],'isplugin'=>0),'saastype');
		if($saastype){
			$data['appsecret']=$data['permanent_code'];
		}
		$data['saastype']=$saastype;
		if($wxwork_app['id']){
			$data['expire']=0;
			pdo_update('core_account_wxwork_app',$data,array('merchid'=>$merchid,'uniacid'=>$_SESSION['uniacid']));
		}else{
			$data['uniacid']=$_SESSION['uniacid'];
			$data['merchid']=$merchid;
			$data['pid']=$pid;
			$data['createtime']=TIMESTAMP;
			pdo_insert('core_account_wxwork_app',$data);
		}
	}
}